package com.jqb.hibernatebbs.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jqb.hibernatebbs.pojo.Bbsmsg;
import com.jqb.hibernatebbs.pojo.Bbsuser;
import com.jqb.hibernatebbs.service.BbsMsgService;


public class MsgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String opt = request.getParameter("opt");
		if("add".equals(opt)){
			request.getRequestDispatcher("/WEB-INF/sendmsg.jsp").forward(request, response);
		}
		if("send".equals(opt)){
			Bbsuser bbsuser = (Bbsuser) request.getSession().getAttribute("user");
			if(bbsuser==null){
				request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
			}else{
				String msg = request.getParameter("msg");
				Bbsmsg bbsmsg = new Bbsmsg();
				bbsmsg.setPoster(bbsuser.getName());
				bbsmsg.setMsg(msg);
				String posttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				bbsmsg.setPosttime(posttime);
				BbsMsgService.newInstance().addMsg(bbsmsg);
				List<Bbsmsg> msgList = BbsMsgService.newInstance().getMsgs();
				System.out.println(msgList.size());
				request.setAttribute("msgList",msgList);
				request.getRequestDispatcher("/WEB-INF/main.jsp").forward(request, response);	
			}
		}
		if("show".equals(opt)){
			List<Bbsmsg> msgList = BbsMsgService.newInstance().getMsgs();
			System.out.println(msgList.size());
			request.setAttribute("msgList",msgList);
			request.getRequestDispatcher("/WEB-INF/main.jsp").forward(request, response);	
		}
	}

}
